<?php

declare (strict_types = 1);

namespace own\interface;

use Closure;
use think\Response;

abstract class OwnMiddlewareInterface
{
    /**
     * 处理请求
     * @param Request   $request
     * @param Closure   $next
     * @return Response
     */
    public function handle($request, Closure $next)
    {
        if ($request->method() == 'OPTIONS') {
            $response = response();
        } else {
            $header = $request->header();
            if(isset($header['authorization'])) {
                $token = str_replace('Bearer ', '', $header['authorization']);
            } else {
                $token = '';
            }
            $response = $this->handleRequest($request, $token, $next);
        }
        // 跨域处理
        return $response->header([
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'POST,GET,PUT,DELETE,OPTIONS',
            'Access-Control-Allow-Headers' => 'X-Requested-With,Content-Type,Token,Authorization,X-Token',
            'Content-Type' => 'application/json; charset=utf-8',
            'Access-Control-Allow-Credentials' => 'false',
            'Access-Control-Max-Age' => 1800
        ]);
    }
    /**
     * 处理请求数据
     * @param  Request $request
     * @param  string  $token
     * @param  Closure  $next
     * @return Response
     */
    abstract public function handleRequest($request, $token, $next);

}
